package org.jsets.fastboot.httputils;

import java.util.Map;
import java.util.function.Consumer;
import org.jsets.fastboot.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Slf4j
public class BodyHttpRequest extends HttpRequest {

	protected static final MediaType MEDIA_TYPE_JSON = MediaType.get("application/json; charset=utf-8");

	private boolean isPut;
	private Object object;
	
	public BodyHttpRequest(String url) {
		super(url);
	}
	
	protected BodyHttpRequest self() {
		return this;
	}
	
	protected BodyHttpRequest post() {
		this.isPut = false;
		return self();
	}
	
	protected BodyHttpRequest put() {
		this.isPut = true;
		return self();
	}
	
	public BodyHttpRequest addHeader(String key, String value) {
		super.addHeader(key, value);
		return self();
	}

	public BodyHttpRequest addHeaders(Map<String, String> headers) {
		super.addHeaders(headers);
		return self();
	}

	public BodyHttpRequest setExceptionHandler(Consumer<Exception> exceptionHandler) {
		super.setExceptionHandler(exceptionHandler);
		return self();
	}
	
	protected BodyHttpRequest setBody() {
		this.isPut = true;
		return self();
	}

	protected Response exchange() {
		try {
			String content;
			if (this.object instanceof String) {
				content = (String) this.object;
			} else {
				content = JsonUtils.toJson(this.object);
			}
			RequestBody body = RequestBody.create(content, MEDIA_TYPE_JSON);
			Request r = null;
			if (this.isPut) {
				r = builder.put(body).build();
			} else {
				r = builder.post(body).build();
			}
			long start = System.currentTimeMillis();
			Response response = HttpClient.getOkHttpClient().newCall(r).execute();
			long elapsed = System.currentTimeMillis() - start;
			log.info("请求地址：{}，耗时：{}毫秒，响应状态：{}", this.url, elapsed, response.code());
			return response;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			if(this.exceptionHandler!=null) {
				this.exceptionHandler.accept(e);
			} else {
				throw new RuntimeException(e.getMessage(), e);
			}
		} 
		return null;
	}
	

}